<template>
  <div>
    <!-- 转任务弹出框 -->
    <CommonDialog
      title="转任务"
      width="76%"
      v-bind:dialogVisible="taskDialogVisible"
      @on-change-dialogVisible="taskChange"
      class="task"
      top="4vh"
    >
      <template #body>
        <!-- insertFormWrap -->
        <el-form
          class="createTaskForm"
          :rules="createTaskFormrules"
          :model="createTaskForm"
          ref="createTaskForm"
          label-position="top"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="TheirProducts" label="关联ID">
                <el-input v-model="createTaskForm.TheirProducts" placeholder="请输入关联ID" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="productName" label="所属产品">
                <el-input v-model="createTaskForm.productName" disabled placeholder="请选择所属产品"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="currentResponsiblePerson" label="当前责任人">
                <el-select
                  v-model="createTaskForm.currentResponsiblePerson"
                  class="userInput"
                  placeholder="责任人"
                  clearable
                  filterable
                  @change="getPersonDepartment"
                >
                  <el-option v-for="(item, index) in insertUserList" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="taskStatus" label="任务状态">
                <el-select
                  v-model="createTaskForm.taskStatus"
                  class="userInput"
                  placeholder="请选择任务状态"
                  disabled
                  clearable
                  filterable
                >
                  <el-option v-for="item in taskStatusList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="taskIdentity" label="任务标识">
                <el-select
                  v-model="createTaskForm.taskIdentity"
                  class="userInput"
                  placeholder="请选择任务标识"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in taskIdentityListC"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="department" label="责任人部门">
                <el-input v-model="createTaskForm.department" placeholder="请输入责任人部门" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="closingDate" label="计划完成时间">
                <el-date-picker
                  :clearable="false"
                  :editable="false"
                  type="date"
                  placeholder="请选择截止日期"
                  :picker-options="pickerOptions"
                  v-model="createTaskForm.closingDate"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="taskType" label="绑定反馈/BUG/需求">
                <el-select
                  v-model="createTaskForm.taskType"
                  class="userInput"
                  placeholder="请选择绑定类型"
                  @change="getFeedBackCloseSet"
                  clearable
                  filterable
                >
                  <el-option v-for="item in taskTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                prop="sourceId"
                label="源ID"
                v-if="createTaskForm.taskType != 0 && createTaskForm.taskType != null"
              >
                <el-select
                  v-model="createTaskForm.sourceId"
                  class="userInput"
                  placeholder="请选择绑定ID"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in bangIdList"
                    :key="item.zenMasterId"
                    :label="item.zenMasterId"
                    :value="item.zenMasterId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item prop="title" label="任务标题">
                <el-input v-model="createTaskForm.title" placeholder="请输入任务标题"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item prop="trackItems" class="updateReason" label="跟踪事项">
                <!-- <vue-tinymce v-model="createTaskForm.trackItems" :setting="setting" /> -->
                <!-- <quill-editor
                  v-model="createTaskForm.trackItems"
                  ref="trackItemsEditor"
                >
                </quill-editor> -->
                <socialUpload :contentDefault="createTaskForm.trackItems" @getContent="getUpdateContent"></socialUpload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #dialog_footer>
        <el-button class="insertCancel" @click="taskDialogVisibleCancle">取 消</el-button>
        <el-button :disabled="isConfirmcreateTaskRow" type="primary" @click="taskCancel('createTaskForm')" class="insertReme">提交</el-button>
      </template>
    </CommonDialog>
  </div>
</template>

<script>
import socialUpload from '../socialUpload/socialUpload.vue'
import CommonDialog from '@/components/commonDialog/commonDialog.vue'
import { taskPandect } from '@/api/tasks/server'
import { FeedBack } from '@/api/feedBack/server'
export default {
    name: '',
    components: {
        CommonDialog,
        socialUpload
    },
    props: {},
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    const _now = Date.now()
                    const seven = 1 * 24 * 60 * 60 * 1000
                    const sevenDays = _now - seven
                    return time.getTime() < sevenDays
                }
            },
            // 控制转任务弹出框的显示和隐藏
            taskDialogVisible: false,
            taskTypeList: [
                {
                    label: '反馈',
                    value: 0
                },
                {
                    label: 'BUG',
                    value: 1
                },
                {
                    label: '需求',
                    value: 2
                }
            ],
            isConfirmcreateTaskRow: true,
            bangIdList: [],
            taskIdentityListC: [
                {
                    label: 'C1',
                    value: 0
                },
                {
                    label: 'C2',
                    value: 1
                }
            ],
            taskStatusList: [
                {
                    label: '新建',
                    value: 0
                },
                {
                    label: '处理中',
                    value: 1
                },
                {
                    label: '已关闭',
                    value: 2
                }
            ],
            insertUserList: [],
            createTaskForm: {
                title: '',
                productId: '',
                productName: '',
                taskStatus: 0,
                TheirProducts: '',
                taskIdentity: 1,
                closingDate: '',
                currentResponsiblePerson: '',
                department: '',
                trackItems: '',
                taskType: 0,
                sourceId: null,
                sourceUrl: null
            },
            tableItemsID: '',
            createTaskFormrules: {
                productId: [{ required: false, message: '请输入任务ID', trigger: 'change' }],
                productName: [{ required: false, message: '请输入关联反馈ID', trigger: 'blur' }],
                taskStatus: [{ required: true, message: '请选择任务状态', trigger: 'change' }],
                TheirProducts: [{ required: false, message: '请输入关联反馈ID', trigger: 'blur' }],
                taskIdentity: [{ required: true, message: '请选择任务标识', trigger: 'change' }],
                closingDate: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
                currentResponsiblePerson: [{ required: true, message: '请选择当前责任人', trigger: 'change' }],
                department: [{ required: false, message: '请选择责任人部门', trigger: 'blur' }],
                trackItems: [{ required: true, message: '请输入跟踪事项', trigger: 'change' }],
                title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
                sourceId: [{ required: true, message: '请输入源ID', trigger: 'change' }]
            },
            setting: {
                branding: false,
                menubar: false,
                toolbar:
          'undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |',
                toolbar_drawer: 'sliding',
                quickbars_selection_toolbar:
          'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
                plugins: 'link image  table lists fullscreen',
                language: 'zh_CN',
                init_instance_callback: editor => {
                    if (this.content) {
                        editor.setContent(this.content)
                    }
                    this.finishInit = true
                    editor.on('NodeChange Change SetContent KeyUp', () => {
                        this.hasChanged = true
                    })
                }, // 上传图片
                convert_urls: false,
                automatic_uploads: true, // 开启点击图片上传时，自动进行远程上传操作
                images_upload_base_path: `${process.env.VUE_APP_GOLDWIND_BASE_API}`, // 图片上传的基本路径
                images_upload_url: '/v2/file/upload',
                images_upload_handler: (blobInfo, success, failure) => {
                    var xhr, formData

                    xhr = new XMLHttpRequest()
                    xhr.withCredentials = false
                    xhr.open('POST', `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/upload')
                    xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token)
                    // xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token);

                    formData = new FormData()
                    formData.append('file', blobInfo.blob())

                    formData.append('checkOfficeFmt', false)
                    formData.append('isTmp', false)
                    xhr.onload = function(e) {
                        var json
                        console.log(e, xhr)
                        console.log(this)

                        if (xhr.errcode == '0') {
                            failure('服务器错误:' + xhr.msg)
                            return
                        }
                        json = JSON.parse(this.responseText)
                        if (!json.data || typeof json.data.fileSourceId != 'string') {
                            failure('服务器错误')
                            return
                        }
                        success(
                            `${process.env.VUE_APP_GOLDWIND_BASE_API}` +
                '/v2/file/download?' +
                '&fileSourceId=' +
                json.data.fileSourceId
                        )
                    }
                    xhr.send(formData)
                },
                image_advtab: false,
                language_url: 'tinymce/langs/zh_CN.js', // 语言包的路径
                elementpath: false, // 隐藏元素路径，不明白的可以切换true/false观察页面
                statusbar: false,
                resize: false,
                height: 200
            }
        }
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {},
    methods: {
        show(_data, _id) {
            this.createTaskForm.TheirProducts = _data
            this.tableItemsID = _id
            this.taskDialogVisible = true
            this.isConfirmcreateTaskRow = true
            this.getProductId(_data)
        },
        taskDialogVisibleCancle() {
            this.$refs['createTaskForm'].resetFields()
            this.taskDialogVisible = false
            this.$emit('refreshPage')
            localStorage.setItem('onSearchID', '反馈ID')
        },
        // 用户输入关联反馈id ，失去焦点查询产品信息
        async getProductId(_id) {
            const feedBackId = _id
            try {
                const result = await taskPandect.GetProductIdByFeedId({ feedBackId: feedBackId })
                if (result.success) {
                    this.createTaskForm.productName = result.data.name
                    const prouctId = result.data.id
                    this.isConfirmcreateTaskRow = false
                    // 根据当前产品ID查询责任人
                    this.insertUserList = []
                    try {
                        const resultList = await FeedBack.GetListItemAsync({ id: prouctId })
                        if (resultList.success) {
                            this.insertUserList = resultList.data
                        }
                    } catch (err) {
                        console.log(err)
                    }
                } else {
                    this.$message.error(result.message)
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 转任务确定接口
        async taskCancel(formName) {
            this.$refs[formName].validate(async valid => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: '数据传输中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    })
                    if (this.createTaskForm.sourceId != null) {
                        for (const item of this.bangIdList) {
                            if (item.zenMasterId === this.createTaskForm.sourceId) {
                                this.createTaskForm.sourceUrl = item.bugUrl
                            }
                        }
                    }

                    const objparams = {
                        ctag: this.createTaskForm.taskIdentity,
                        expectedCompletedDate: this.createTaskForm.closingDate,
                        feedBackId: this.createTaskForm.TheirProducts,
                        responsibleUser: this.createTaskForm.currentResponsiblePerson,
                        status: this.createTaskForm.taskStatus,
                        trackingTip: this.createTaskForm.trackItems,
                        title: this.createTaskForm.title,
                        taskType: this.createTaskForm.taskType,
                        sourceId: this.createTaskForm.sourceId,
                        sourceUrl: this.createTaskForm.sourceUrl
                    }
                    try {
                        const result = await taskPandect.FeedBackTurnToTheTask(objparams)
                        if (result.success) {
                            localStorage.setItem('onSearchID', '反馈ID')
                            loading.close()
                            this.createTaskForm = {
                                title: '',
                                productId: '',
                                productName: '',
                                taskStatus: 0,
                                TheirProducts: '',
                                taskIdentity: 1,
                                closingDate: '',
                                currentResponsiblePerson: '',
                                department: '',
                                trackItems: '',
                                taskType: 0,
                                sourceId: null,
                                sourceUrl: null
                            }
                            this.taskDialogVisible = false
                            this.$emit('refreshPage')
                            this.$refs[formName].resetFields()
                        } else {
                            localStorage.setItem('onSearchID', '反馈ID')
                            loading.close()
                        }
                    } catch (err) {
                        loading.close()
                        console.log(err)
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        taskChange(val) {
            this.taskDialogVisible = val
            this.$emit('refreshPage')
            localStorage.setItem('onSearchID', '反馈ID')
            this.$refs['createTaskForm'].resetFields()
        },
        getPersonDepartment(_val) {
            this.createTaskForm.department = ''
            this.insertUserList.forEach(item => {
                if (item.id == _val) {
                    this.createTaskForm.department = item.department
                }
            })
        },
        /**
     * @description: 获得转任务跟踪事项
     * @param {String} Value
     */
        getUpdateContent(Value) {
            this.createTaskForm.trackItems = Value
        },
        async getFeedBackCloseSet(_val) {
            this.bangIdList = []
            this.createTaskForm.sourceId = null
            if (_val === 1) {
                try {
                    const result = await FeedBack.GetChangeBugByFeedBack({
                        feedbackId: this.tableItemsID
                    })
                    if (result.success) {
                        this.bangIdList = result.data
                    }
                } catch (error) {
                    console.log(error)
                }
            } else {
                try {
                    const result = await FeedBack.GetChangeStoryByFeedBack({
                        feedbackId: this.tableItemsID
                    })
                    if (result.success) {
                        this.bangIdList = result.data
                    }
                } catch (error) {
                    console.log(error)
                }
            }
            //  根据当前id 获得解决方案下拉列表
        }
    }
}
</script>

<style scoped lang="less">
.createTaskForm {
  .userSelect {
    width: 100%;
    height: 30px;
  }
  .userInput {
    width: 100%;
    height: 30px;
  }
  .taskTitle {
    width: 100%;
    height: 30px;
  }
}
::v-deep .ql-editor {
  height: 130px;
}
</style>
